import pool from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export class BaseModel {
  protected tableName: string;

  constructor(tableName: string) {
    this.tableName = tableName;
  }

  // 查找所有记录
  async findAll<T extends RowDataPacket>(conditions: object = {}) {
    const whereClause = Object.entries(conditions)
      .map(([key]) => `${key} = ?`)
      .join(' AND ');

    const values = Object.values(conditions);
    const sql = `SELECT * FROM ${this.tableName}${
      whereClause ? ` WHERE ${whereClause}` : ''
    }`;

    const [rows] = await pool.query<T[]>(sql, values);
    return rows;
  }

  // 根据ID查找记录
  async findById<T extends RowDataPacket>(id: number | string) {
    const [rows] = await pool.query<T[]>(
      `SELECT * FROM ${this.tableName} WHERE id = ?`,
      [id]
    );
    return rows[0];
  }

  // 创建记录
  async create(data: object) {
    const keys = Object.keys(data);
    const values = Object.values(data);
    const sql = `INSERT INTO ${this.tableName} (${keys.join(
      ', '
    )}) VALUES (${keys.map(() => '?').join(', ')})`;

    const [result] = await pool.query<ResultSetHeader>(sql, values);
    return result;
  }

  // 更新记录
  async update(id: number | string, data: object) {
    const sets = Object.keys(data)
      .map(key => `${key} = ?`)
      .join(', ');
    const values = [...Object.values(data), id];
    const sql = `UPDATE ${this.tableName} SET ${sets} WHERE id = ?`;

    const [result] = await pool.query<ResultSetHeader>(sql, values);
    return result;
  }

  // 删除记录
  async delete(id: number | string) {
    const [result] = await pool.query<ResultSetHeader>(
      `DELETE FROM ${this.tableName} WHERE id = ?`,
      [id]
    );
    return result;
  }

  // 分页查询
  async findWithPagination<T extends RowDataPacket>(
    page: number = 1,
    pageSize: number = 10,
    conditions: object = {}
  ) {
    const offset = (page - 1) * pageSize;
    const whereClause = Object.entries(conditions)
      .map(([key]) => `${key} = ?`)
      .join(' AND ');
    const values = Object.values(conditions);

    // 获取总数
    const [countRows] = await pool.query<RowDataPacket[]>(
      `SELECT COUNT(*) as total FROM ${this.tableName}${
        whereClause ? ` WHERE ${whereClause}` : ''
      }`,
      values
    );
    const total = countRows[0].total;

    // 获取分页数据
    const sql = `SELECT * FROM ${this.tableName}${
      whereClause ? ` WHERE ${whereClause}` : ''
    } LIMIT ? OFFSET ?`;
    const [rows] = await pool.query<T[]>(sql, [...values, pageSize, offset]);

    return {
      data: rows,
      pagination: {
        current: page,
        pageSize,
        total
      }
    };
  }
} 